package com.example.easynote;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;


import java.io.IOException;


import java.net.MalformedURLException;



import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;

import android.content.Context;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;

import android.os.StrictMode;
import android.provider.MediaStore;

import android.util.Log;
import android.view.Menu;

import android.widget.Toast;

import com.easynote.UI.BaseRequestListener;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.UiLifecycleHelper;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;


import com.facebook.widget.FacebookDialog;

public class ConnectFacebook extends Activity
{

	private static String APP_ID = "793316947352440";
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	private SharedPreferences mPrefs;
	private UiLifecycleHelper uiHelper;
	Context context;
	//SocialAuthAdapter adapter;
	//adapter = 
	private Handler mHandler;
	ProgressDialog dialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	   // setContentView(R.layout.main);
	    mFacebook = new Facebook(APP_ID);
	    mAsyncRunner = new AsyncFacebookRunner(mFacebook);
	    //hareEmail();
	    //Implementing SSO
	    mPrefs = getPreferences(MODE_PRIVATE);
	    String access_token = mPrefs.getString("access_token", null);
	    long expires = mPrefs.getLong("access_expires", 0);
	 
	    if (access_token != null) {
	        mFacebook.setAccessToken(access_token);
	    }
	 
	    if (expires != 0) {
	        mFacebook.setAccessExpires(expires);
	    }
	    if(mFacebook.isSessionValid())
	    {
	    	sharePicture();
	    	
	    }
	    else
	    {
	    	 mFacebook.authorize(this, new String[]{"email", "publish_checkins", "publish_stream"}, new DialogListener()
	    	 {
	 	    	
	 	        public void onComplete(Bundle values) 
	 	        {

	 	        	sharePicture();
	 	            Toast.makeText(getApplicationContext(), "Picture Shared Successfully", Toast.LENGTH_SHORT).show();
	 	            //CardShared.this.finish();
	 	        }


	 	        public void onFacebookError(FacebookError e) {
	 	            Log.d("FACEBOOK ERROR","FB ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
	 	        }


	 	        public void onError(DialogError e) {
	 	            Log.e("ERROR","AUTH ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
	 	        }


	 	        public void onCancel() {
	 	            Log.d("CANCELLED","AUTH CANCELLED");
	 	        }
	 	    });
	    }
	   
	}

	//updating Status
	public void sharePicture()
	{
		
		Intent intent = getIntent();
		String fname = intent.getStringExtra("dir");
		Uri uri = Uri.parse(fname);
		Bitmap image = null;
		try {
			image = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(image == null)
		{
			Toast.makeText(getApplicationContext(), " NULL", Toast.LENGTH_SHORT).show();
		}
	    byte[] data = null;
	    
	    try {
	        //Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.camera);
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
	        data = baos.toByteArray();
	        Bundle params = new Bundle();
	        //params.putString("method", "photos.upload");
	        params.putString(Facebook.TOKEN, mFacebook.getAccessToken());
	        params.putString("message", "message");
	        params.putByteArray("picture", data);
	        //params.putString("caption", "caption");
	        mAsyncRunner.request("me/photos", params, "POST",
	                new SampleUploadListener(), null);
	        
	    } catch (Exception e) 
	    {
	        e.printStackTrace();
	        Toast.makeText(getApplicationContext(), " not Picture Shared Successfully", Toast.LENGTH_SHORT).show();
	    }

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
	    super.onActivityResult(requestCode, resultCode, data);

	    Log.d("onActivityResult","onActivityResult");
	    mFacebook.authorizeCallback(requestCode, resultCode, data);
	}
	public class SampleUploadListener extends BaseRequestListener {

	    public void onComplete(final String response, final Object state) {
	        try {

	            Log.d("Facebook-Example", "Response: " + response.toString());
	            JSONObject json = Util.parseJson(response);
	            final String f = json.getString("src");

	        } catch (JSONException e) {
	            Log.w("Facebook-Example", "JSON Error in response");
	        } catch (FacebookError e) {
	            Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
	        }
	    }
	}
	
	
	
	
}
